import json
from datetime import datetime

from sqlalchemy.cyextension.processors import time_cls


def process_booking_data(response_data, site_num, time_period):
    """
    处理预订系统响应数据，允许用户选择场地和时间段
    :param response_data: POST请求返回的JSON数据
    :param site_num: 场地编号（从1开始）
    :param time_period: 时间段选择（"早"、"中"、"晚"）
    :return: 用户选择的场地和时间段信息
    """
    # 解析JSON数据
    try:
        data = json.loads(response_data)
    except json.JSONDecodeError:
        print("错误：响应数据不是有效的JSON格式")
        return None

    # 创建场地选择菜单
    print("\n=== 可用场地 ===")
    venues = {}
    for i, venue_sessions in enumerate(data):
        if venue_sessions:  # 确保场地有时间段数据
            venue_name = venue_sessions[0]["placeName"]
            venues[i] = venue_name
            print(f"{i + 1}. {venue_name}")

    # 用户选择场地
    #venue_choice = int(input("\n请选择场地编号: ")) - 1
    venue_choice = site_num-1
    if venue_choice not in venues:
        print("错误：无效的场地选择")
        return None

    selected_venue = data[venue_choice]
    venue_name = selected_venue[0]["placeName"]

    # 根据实际时间判断早中晚时间段
    morning_sessions = []   # 早上时间段 (例如 00:00-12:00)
    noon_sessions = []      # 中午时间段 (例如 12:00-17:00)
    evening_sessions = []   # 晚上时间段 (例如 17:00-24:00)
    
    for session in selected_venue:
        start_hour = int(session["openStartTime"].split(":")[0])
        if start_hour < 12:
            morning_sessions.append(session)
        elif start_hour < 17:
            noon_sessions.append(session)
        else:
            evening_sessions.append(session)
    
    # 根据用户选择的时间段确定返回的数据
    selected_sessions = []
    if time_period == "早":
        selected_sessions = morning_sessions
    elif time_period == "中":
        selected_sessions = noon_sessions
    elif time_period == "晚":
        selected_sessions = evening_sessions
    else:
        print("错误：无效的时间段选择，应为'早'、'中'或'晚'")
        return None

    if not selected_sessions:
        print(f"错误：所选场地在'{time_period}'时间段内没有可用的时间段")
        return None

    # 创建时间段选择菜单
    print(f"\n=== {venue_name} 可用时间段 ===")
    time_slots = {}
    for j, session in enumerate(selected_venue):
        start_time = datetime.strptime(session["openStartTime"], "%H:%M:%S").strftime("%H:%M")
        end_time = datetime.strptime(session["openEndTime"], "%H:%M:%S").strftime("%H:%M")
        date = datetime.strptime(session["openDate"], "%Y-%m-%d").strftime("%Y-%m-%d")
        status = "已满" if session["sessionsStatus"] == "FULLY_BOOKED" else "可预订"

        time_slot = f"{date} {start_time}-{end_time} ({status})"
        time_slots[j] = {
            "display": time_slot,
            "data": session
        }
        print(f"{j + 1}. {time_slot}")

    # 根据用户选择的时间段过滤出对应的索引
    selected_time_slots = []
    for j, session in enumerate(selected_venue):
        if session in selected_sessions:
            selected_time_slots.append(time_slots[j])

    # 返回所有选中的时间段信息
    sessions_data = [session["data"] for session in selected_time_slots]
    sessions_display = [session["display"] for session in selected_time_slots]
    
    return {
        "venue_name": venue_name,
        "time_slots": sessions_display,  # 返回所有选中的时间段显示文本
        "ids": [session["data"]["id"] for session in selected_time_slots],  # 返回所有选中的时间段ID
        "openingPeriodIds": [session["data"]["openingPeriodId"] for session in selected_time_slots],  # 返回所有openingPeriodId
        "placeIds": [session["data"]["placeId"] for session in selected_time_slots],  # 返回所有placeId
        "selected_sessions": sessions_data  # 返回所有选中的时间段完整数据
    }


# 示例使用
if __name__ == "__main__":
    # 假设这是从POST请求获取的响应数据
    with open("response2.json", "r", encoding="utf-8") as f:
        response_data = f.read()

    result = process_booking_data(response_data, site_num=1, time_period="晚")

    if result:
        print("\n=== 您的选择 ===")
        print(f"场地: {result['venue_name']}")
        print("时间段:")
        for i, time_slot in enumerate(result['time_slots']):
            print(f"  {time_slot}")
            print(f"    ID: {result['ids'][i]}")
            print(f"    Opening Period ID: {result['openingPeriodIds'][i]}")
            print(f"    Place ID: {result['placeIds'][i]}")